#d5ef3448b818ae7a1a9c74eebbe6923b
import cv2
import requests
import numpy as np
import pytesseract
import json
picUrl1="https://"
picUrl2="https://"
output_path='diffpic.png'


def compare_images(url1, url2, output_path):
    # Download the images
    response1 = requests.get(url1)
    image1 = np.asarray(bytearray(response1.content), dtype="uint8")
    image1 = cv2.imdecode(image1, cv2.IMREAD_COLOR)
    response2 = requests.get(url2)
    image2 = np.asarray(bytearray(response2.content), dtype="uint8")
    image2 = cv2.imdecode(image2, cv2.IMREAD_COLOR)

    # Convert the images to grayscale
    gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)

    # Compute the absolute difference between the two images
    diff = cv2.absdiff(gray1, gray2)

    # Threshold the difference image
    # bug modify
    thresh = cv2.threshold(diff, 5, 255, cv2.THRESH_BINARY)[1]

    # Find the contours in the thresholded image
    contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Draw the contours on the original images
    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(image1, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv2.rectangle(image2, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # Perform OCR on the first image
    text1 = pytesseract.image_to_string(gray1)

    # Perform OCR on the second image
    text2 = pytesseract.image_to_string(gray2)

    # Create JSON objects with the OCR results
    result1 = {
        "text": text1
    }
    result2 = {
        "text": text2
    }
    json_result1 = json.dumps(result1)
    json_result2 = json.dumps(result2)

    # Compare the JSON objects
    if json_result1 == json_result2:
        print("The text is the same")
    else:
        print("The text is different")
        print("result1:") # add
        print(json_result1) # add
        print("result2:") # add
        print(json_result2) # add


    # Combine the two images
    result_image = np.concatenate((image1, image2), axis=1)

    # Write the result to a file
    # bug here
    cv2.imwrite(output_path, result_image)

    # Display the result
    cv2.imshow("Result", result_image)
    cv2.waitKey(0)

    # Return the JSON objects
    return json_result1, json_result2

compare_images(picUrl1,picUrl2,output_path)
